package com.macro.admin.service.impl;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.macro.admin.service.CaptchaService;
import com.macro.admin.utils.SmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码相关接口
 *
 * @Author: Xiao Hai
 * @Date: 2021-04-21 08:20:35
 * @since 1.0.0
 */
@Slf4j
@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${aliyun.mouldId}")
    private String mould;

    @Override
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        //定义response输出类型为image
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");

        //-------------------生成验证码 begin --------------------------
        // 获取验证码文本内容
        String text = defaultKaptcha.createText();
        log.info("验证码内容:" + text);
        //将验证码放入session中
        request.getSession().setAttribute("captcha", text);
        //根据文本内容创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(text);

        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            //输出流输出图片，格式jpg
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (null != outputStream) {
                try {

                    outputStream.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //-------------------生成验证码 end ---------------------------- }
    }


    @Override
    public int SmsCode(String phone){
        int random = ((int)((Math.random()*9+1)*100000));
        log.info("生成随机数："+random);
        try {
            SmsUtils.sendSms(phone, mould, "{\"code\":\"" + random + "\"}");
            redisTemplate.opsForValue().set(phone,random,2L, TimeUnit.MINUTES);
            return random;
        }catch (Exception e){
            log.error("短信发送失败，错误信息为："+e.getMessage());
        }

        return 0;
    }
}
